export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    row: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  watch: {
    visible: {
      handler: function() {
        if (this.visible) {
          return this.onVisible();
        }
      },
      immediate: true
    }
  },
  computed: {
    isCreate() {
      return !this.row;
    },
    title() {
      return this.isCreate ? "新增" : "编辑";
    }
  },
  methods: {
    // 显示
    onVisible() {},
    // 隐藏
    onHidden(type) {
      if (typeof this.initData !== "function") {
        throw new Error("initData 不是一个函数!");
      }
      this.params = this.initData();
      this.$emit("update:visible", false);
      // 避免关闭切换状态时闪烁
      setTimeout(() => this.$emit("update:row", null), 300);
      this.$refs.forms && this.$refs.forms.resetFields();
      if (type === "cancel") {
        this.$emit("cancel");
      }
      if (type === "ok") {
        this.$emit("hidden");
      }
    },
    // 取消
    onCancel() {
      this.onHidden("cancel");
    },
    validateField(name) {
      return new Promise((resolve, reject) => {
        this.$refs.forms.validateField(name, error => {
          if (error) reject(false);
          else resolve(true);
        });
      });
    }
  }
};
